//
//  InZhuCeViewController.m
//  Inner  Voice
//
//  Created by 逗比小胖！ on 16/3/8.
//  Copyright © 2016年 徐海宇. All rights reserved.
//

#import "InZhuCeViewController.h"
#import "InManagementViewController.h"
#import <SMS_SDK/SMSSDK.h>
#import "MBProgressHUD+BWMExtension.h"
#import <AFNetworking.h>
#import "UserModel.h"
#import "UIImage+ResizeImage.h"
#import "InLoginViewController.h"

@interface InZhuCeViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UIAlertViewDelegate>

//密码
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;

//头像
@property (weak, nonatomic) IBOutlet UIImageView *iconImage;
//昵称
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
//菊花
@property (nonatomic,strong)MBProgressHUD *hud;
//注册中
@property(nonatomic,assign)BOOL registing;

//是否上传头像
@property(nonatomic,assign)BOOL isUpLoadIcon;
//头像路径
@property(nonatomic,copy)NSString *iconPath;
//缩略头像路径
@property(nonatomic,copy)NSString *siconPath;
//返回用户的id
@property(nonatomic,copy)NSString *userId;

@property(nonatomic,strong)NSTimer *timer;

@property(nonatomic,assign)NSInteger number;

@end

@implementation InZhuCeViewController

- (instancetype)initWithTel:(NSString *)tel {
    if (self = [super init]) {
        self.userTel = tel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.iconImage.image = [UIImage imageNamed:@"icon.jpg"];
    self.isUpLoadIcon = NO;
    self.iconPath = @"";
    self.siconPath = @"";

    // Do any additional setup after loading the view from its nib.
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:{
            //拍照
            [self showImagePickerViewWithSourceType:UIImagePickerControllerSourceTypeCamera];
        }   break;
        case 1:{
            //打开相册
            [self showImagePickerViewWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        }   break;
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)showImagePickerViewWithSourceType:(UIImagePickerControllerSourceType)sourceType {    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    
    [picker setSourceType:sourceType];
    [picker setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
    [picker setAllowsEditing:YES];
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSLog(@"注册 %@",[info[UIImagePickerControllerEditedImage] class]);
    //读取图片
    UIImage *img = info[UIImagePickerControllerEditedImage];
    
    self.iconImage.image = [UIImage reSizeImage:img toSize:CGSizeMake(self.view.frame.size.width/2, self.view.frame.size.width/2)];
    
    self.isUpLoadIcon = YES;
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (NSString *)imagePath{
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"iconImage.jpg"];
    return path;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//返回
- (IBAction)backToBtn:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)choiceBtnClick:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"上传照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择",nil];
    actionSheet.delegate = self;
    [actionSheet showInView:self.view];

}

//确定
- (IBAction)doneBtnClick:(id)sender {
    if (self.nameTextField.text.length <= 3||self.nameTextField.text.length > 10) {
        [self showAlertView:@"昵称的长度不符合规定" withDelegate:nil withTag:1000];
        return;
    }
    if (self.passwordTextField.text.length < 6||self.passwordTextField.text.length >20) {
        [self showAlertView:@"密码的长度不符合规定" withDelegate:nil withTag:1001];
    }
    if((self.nameTextField.text.length > 3&& self.nameTextField.text.length <= 10)&&(self.passwordTextField.text.length >= 6 && self.passwordTextField.text.length <= 20)){
        if(self.isUpLoadIcon == YES){
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [self uploadUserIcon];
        }else{
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [self sendRegistInfo];
        }
    }
}

#pragma make -  发送注册信息
- (void)sendRegistInfo{
    if ([AppDelegate shareAppdelegate].canConnectedToTheInternet) {

    self.view.userInteractionEnabled = NO;
    NSDictionary *dic = @{@"name":self.nameTextField.text,
                          @"password":self.passwordTextField.text,
                          @"tel":self.userTel,
                          @"icon":self.iconPath,
                          @"sicon":self.siconPath};
    NSString *url = @"http://wangtest11.applinzi.com/home/Banner/regist";
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.responseSerializer = [AFJSONResponseSerializer serializer];
    [manger POST:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"_____________注册_____________%@",responseObject);
        if([responseObject isKindOfClass:[NSDictionary class]]){
            if ([responseObject[@"code"] isEqualToString:@"2"]) {
                NSString *str = responseObject[@"data"];
                self.userId = str;
                UserModel *user = [[UserModel alloc]init];
                user.u_id = str;
                user.name = self.nameTextField.text;
                user.password = self.passwordTextField.text;
                user.tel = self.userTel;
                user.icon = self.iconPath;
                user.sicon = self.siconPath;
                
                [AppDelegate shareAppdelegate].userModel = user;
                
                [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"u_id"];
                [[NSUserDefaults standardUserDefaults]setObject:user.name forKey:@"u_id"];
                
                if(self.isUpLoadIcon == YES){
                    //拿到编辑过的照片
                    NSData *data = UIImageJPEGRepresentation(self.iconImage.image, 0);
                    //写入沙盒
                    [data writeToFile:[self imagePath] atomically:YES];
                    //保存路径
                    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"icon"];
                    [[NSUserDefaults standardUserDefaults]setObject:[self imagePath] forKey:@"icon"];
                }
                
                [[NSUserDefaults standardUserDefaults]setObject:dic forKey:@"userDict"];
                [self showAlertView:@"注册成功" withDelegate:self withTag:2000];
//                [[NSNotificationCenter defaultCenter]postNotificationName:@"aaaaa" object:self userInfo:@{@"usermodel":user}];
            }else{
                self.isUpLoadIcon = NO;
                [self showAlertView:responseObject[@"data"] withDelegate:nil withTag:1];
            }
        }else{
            NSLog(@"注册%@",responseObject);
        }
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"注册%@",error);
        self.view.userInteractionEnabled = YES;
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self showAlertView:@"网络连接失败" withDelegate:nil withTag:1];
    }];
    }else {
        [self showAlertView:@"当前网络不可用"];
    }
}
#pragma mark - 封装UIAlertView方法，直接调用就可以显示提示
-(void)showAlertView:(NSString *)string {
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:string delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
    
}
#pragma mark - 上传图片
- (void)uploadUserIcon {
    if ([AppDelegate shareAppdelegate].canConnectedToTheInternet) {

    self.view.userInteractionEnabled = NO;
    NSString *urlPath = @"http://wangtest11.applinzi.com/home/Banner/uploadIcon";
    [[AFHTTPSessionManager manager] POST:urlPath parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = UIImageJPEGRepresentation(self.iconImage.image, 1.0);
        [formData appendPartWithFileData:data name:@"icon" fileName:@"img.png" mimeType:@"text/html"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"上传图片成功%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            if ([responseObject[@"code"] isEqualToString:@"1"]) {
                NSDictionary *dict = responseObject[@"data"];
                NSLog(@"注册 %@",dict);
                //截取文件名
                NSString *iconName = dict[@"savename"];
                //截取大图url
                NSString *iconUrl = dict[@"url"];
                //搜索文件名的位置
                NSRange range = [iconUrl rangeOfString:iconName];
                //截取文件url路径
                NSMutableString *urlPath = [NSMutableString stringWithString:iconUrl];
                [urlPath deleteCharactersInRange:range];
                //拼字符串，获取缩略图的路径
                NSString *s_icon = [NSString stringWithFormat:@"%@thumb_%@",urlPath,iconName];
                self.siconPath = s_icon;
                self.iconPath = iconUrl;
                [self sendRegistInfo];
            } else {
                self.isUpLoadIcon = NO;
                self.iconImage.image = [UIImage imageNamed:@"icon.jpg"];
                self.view.userInteractionEnabled = YES;
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                [self showAlertView:@"图片上传失败222" withDelegate:nil withTag:1];
            }
        } else {
            self.isUpLoadIcon = NO;
            self.iconImage.image = [UIImage imageNamed:@"icon.jpg"];
            self.view.userInteractionEnabled = YES;
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [self showAlertView:@"图片上传失败000" withDelegate:nil withTag:1];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        self.isUpLoadIcon = NO;
        self.iconImage.image = [UIImage imageNamed:@"icon.jpg"];
        self.view.userInteractionEnabled = YES;
        if (error) {
            NSLog(@"注册 %@",error);
            [self showAlertView:@"图片上传失败111" withDelegate:nil withTag:1];
        }
    }];
    }
}

//封装UIAlertView方法，直接调用就可以显示提示
-(void)showAlertView:(NSString *)string withDelegate:(id<UIAlertViewDelegate>)delegate withTag:(NSInteger)tagCount {
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:string delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.delegate = delegate;
    alertView.tag=tagCount;
    [alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 2000 && buttonIndex == 1) {
        NSLog(@"注册 确认");
        //返回用户主页
        InMainTabBarViewController *con = [[InMainTabBarViewController alloc]init];
        [self presentViewController:con animated:YES completion:nil];
    }
}



- (void)dealloc {

    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
